import { Request, Response, NextFunction } from 'express';
import multer, { FileFilterCallback, Multer } from 'multer';
import path from 'path';
import { UploadConfig } from '../types/file-request';
import { ApiError } from '../utils/ApiError';
import { StatusCodes } from '../constants/statusCodes';

const defaultConfig: UploadConfig = {
  fieldName: 'file',
  destination: 'uploads/',
  fileTypes: ['.json', '.csv', '.sql'],
  maxSize: 10 * 1024 * 1024, // 10MB
};

export const createUploadMiddleware = (config: Partial<UploadConfig> = {}) => {
  const finalConfig = { ...defaultConfig, ...config };

  const storage = multer.diskStorage({
    destination: (_req: Request, _file: multer.File, cb: (error: Error | null, destination: string) => void) => {
      cb(null, finalConfig.destination);
    },
    filename: (_req: Request, file: multer.File, cb: (error: Error | null, filename: string) => void) => {
      const uniqueSuffix = `${Date.now()}-${Math.round(Math.random() * 1E9)}`;
      cb(null, `${file.fieldname}-${uniqueSuffix}${path.extname(file.originalname)}`);
    },
  });

  const fileFilter = (_req: Request, file: multer.File, cb: FileFilterCallback) => {
    const ext = path.extname(file.originalname).toLowerCase();
    if (finalConfig.fileTypes.includes(ext)) {
      cb(null, true);
    } else {
      cb(new ApiError(StatusCodes.BAD_REQUEST, `仅支持以下文件类型: ${finalConfig.fileTypes.join(', ')}`));
    }
  };

  return multer({
    storage,
    fileFilter,
    limits: {
      fileSize: finalConfig.maxSize,
    },
  }).single(finalConfig.fieldName);
};

// 为不同类型的上传创建预配置的中间件
export const uploadMiddleware = {
  data: createUploadMiddleware({
    fieldName: 'data',
    fileTypes: ['.json'],
    maxSize: 5 * 1024 * 1024, // 5MB
  }),

  backup: createUploadMiddleware({
    fieldName: 'backup',
    fileTypes: ['.sql'],
    maxSize: 100 * 1024 * 1024, // 100MB
    destination: 'backups/',
  }),

  // 添加其他预配置的上传中间件...
};
